import xingzhuang_image from '@/assets/images/xingzhuang.svg';
import services from '@/services/dict';
import {
  ActionType,
  PageContainer,
  ProCard,
  ProColumns,
  ProFormSelect,
  ProList,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, message, Modal } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import CreateForm from './components/CreateForm';
import EditForm, { FormValueType } from './components/EditForm';

const {
  addDict,
  subLevel,
  dictPage,
  editBaseInfo,
  deleteByCodes,
  enabled,
  disable,
} = services.DictController;

// 字典集顶级菜单项类型定义
interface DictTopItem {
  title: string;
  avatar?: string;
  code: string;
  // actions: JSX.Element[];
}

const TableList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [selectedDictCode, setSelectedDictCode] = useState<DictTopItem | null>(
    null,
  );
  const actionRef = useRef<ActionType>();
  const [dictTops, setDictTops] = useState<DictTopItem[]>([]);

  // 编辑
  const [editModalVisible, handleEditModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});

  // 获取顶级字典集数据
  const fetchTopDictData = async () => {
    try {
      const { data } = await subLevel('0');
      if (data) {
        const formattedData = data.map((item) => ({
          title: item.name,
          avatar: xingzhuang_image,
          code: item.code,
          // actions: [
          //   <a key="invite" onClick={() => handleAddDict(item.code)}>新增项</a>,
          // ],
        }));
        setDictTops(formattedData);
      }
    } catch (error) {
      message.error('获取字典集数据失败');
    }
  };

  // 处理字典集点击事件
  const handleDictTopClick = (code: string, title: string) => {
    setSelectedDictCode({ code, title });
  };

  // 初始加载和字典集选择时触发数据重载
  useEffect(() => {
    fetchTopDictData();
  }, []);

  // 当选中的字典集变化时，重新加载表格数据
  useEffect(() => {
    if (selectedDictCode) {
      // 安全地调用 reload
      actionRef.current?.reload?.().catch((error) => {
        message.error('加载字典项失败');
      });
    }
  }, [selectedDictCode]);

  // 初始化时默认渲染第一个字典集的字典项
  useEffect(() => {
    if (dictTops.length > 0 && !selectedDictCode) {
      setSelectedDictCode(dictTops[0]);
    }
    if (selectedDictCode) {
      actionRef.current?.reload?.().catch((error) => {
        message.error('加载字典项失败');
      });
    }
  }, [dictTops, selectedDictCode]);

  // 删除字典项
  const handleRemove = async (id: number) => {
    const hide = message.loading('正在删除');
    if (!id) return true;
    try {
      await deleteByCodes([id]);
      hide();
      message.success('删除成功');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  /**
   * 编辑字典
   * @param fields
   */
  const handleUpdate = async (fields: FormValueType) => {
    const hide = message.loading('正在编辑');
    try {
      // 确保 fields.id 存在
      if (!fields.id) {
        message.error('字典 ID 不能为空');
        return false;
      }
      await editBaseInfo({
        id: fields.id,
        name: fields.name || '',
        val: fields.val || '',
        sort: fields.sort,
      });
      hide();
      message.success('编辑成功');
      return true;
    } catch (error) {
      hide();
      // message.error('添加失败请重试！');
      return false;
    }
  };

  // 切换字典项状态
  const handleToggleStatus = async (record: API.Dictionary) => {
    const hide = message.loading('正在处理');
    try {
      record.status === 1
        ? await disable(record.code)
        : await enabled(record.code);
      hide();
      message.success(`${record.status === 1 ? '禁用' : '启用'}成功`);
      if (actionRef.current) {
        actionRef.current.reload();
      }
      return true;
    } catch (error) {
      hide();
      message.error('操作失败，请重试');
      return false;
    }
  };

  // 字典项表格列定义
  const dictSubs: ProColumns<API.Dictionary>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      tooltip: '唯一的 key',
      hideInForm: true,
      hideInTable: true,
      search: false,
    },
    {
      title: '代码',
      dataIndex: 'code',
      tooltip: '唯一的 key',
      hideInForm: true,
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '代码为必填项',
          },
        ],
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '自定义值',
      dataIndex: 'val',
      tooltip:
        '如：未知男女的标准值为：0，1，2 而我们的code是100001,100002,10003，此时这里的自定义值就用上了，此值为用户输入',
      valueType: 'text',
    },
    {
      title: '父级代码',
      dataIndex: 'parentCode',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      valueType: 'digit',
      initialValue: 1,
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: { text: '禁用', status: '0' },
        1: { text: '启用', status: '1' },
      },
      valueType: 'select',
      search: {
        transform: (value) => (value === '1' ? 1 : 0),
      },
      // Default value for the form
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          // Apply default value only for the form, not search
          return (
            <ProFormSelect
              {...rest}
              valueEnum={{
                0: '禁用',
                1: '启用',
              }}
              fieldProps={{
                defaultValue: '1',
                placeholder: '请选择状态',
              }}
            />
          );
        }
        return defaultRender(item);
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              Modal.confirm({
                title: '确认删除',
                content: `确定要删除字典 ${record.name} 吗？`,
                okText: '确认',
                okType: 'danger',
                cancelText: '取消',
                onOk: async () => {
                  const success = await handleRemove(record.id);
                  if (success) {
                    actionRef.current?.reloadAndRest?.();
                  }
                },
              });
            }}
          >
            删除
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              Modal.confirm({
                title: `确认${record.status === 1 ? '禁用' : '启用'}`,
                content: `确定要${record.status === 1 ? '禁用' : '启用'} 字典 ${
                  record.name
                } 吗？`,
                okText: '确认',
                okType: 'primary',
                cancelText: '取消',
                onOk: async () => {
                  await handleToggleStatus(record);
                },
              });
            }}
          >
            {record.status === 1 ? '禁用' : '启用'}
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleEditModalVisible(true);
              setStepFormValues(record);
            }}
          >
            编辑
          </a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProCard>
        <ProCard title="字典集" colSpan="20%">
          <ProList<DictTopItem>
            ghost={true}
            pagination={{
              showTotal: (total) => `共${total}个字典集`,
              defaultPageSize: 4,
              showSizeChanger: false,
              showQuickJumper: false,
              simple: { readOnly: true }, // 使用简单分页样式
            }}
            rowSelection={{
              type: 'radio',
              defaultSelectedRowKeys: [0], // 设置默认选中第一项[数据下标]
              getCheckboxProps: () => ({ disabled: true, display: 'none' }),
            }}
            showActions="hover"
            grid={{ gutter: 16, column: 1 }}
            metas={{
              title: {},
              subTitle: {},
              type: {},
              avatar: {},
              content: {},
              // actions: {},
            }}
            dataSource={dictTops}
            onItem={(record) => ({
              onClick: () => handleDictTopClick(record.code, record.title),
            })}
          />
        </ProCard>

        <ProCard title="字典项" headerBordered>
          <ProTable<API.Dictionary>
            actionRef={actionRef}
            rowKey="id"
            search={false}
            toolBarRender={() => [
              <Button
                key="1"
                type="primary"
                onClick={() => handleModalVisible(true)}
              >
                新增
              </Button>,
            ]}
            pagination={{
              defaultPageSize: 8,
              showSizeChanger: false,
            }}
            request={async (params) => {
              try {
                if (!selectedDictCode) {
                  return {
                    data: [],
                  };
                }
                const { data, success } = await subLevel(selectedDictCode.code);
                return {
                  data: data,
                  success: success ?? true,
                };
              } catch (error) {
                message.error('加载字典项失败');
                return {
                  data: [],
                };
              }
            }}
            columns={dictSubs}
          ></ProTable>
        </ProCard>

        <CreateForm
          onCancel={() => handleModalVisible(false)}
          modalVisible={createModalVisible}
          title={`新增${selectedDictCode?.title}字典项`}
        >
          <ProTable<API.Dictionary, API.DictionaryAdd>
            onSubmit={async (value) => {
              if (!selectedDictCode) {
                message.error('请选择字典集');
                return;
              }
              const addFields = { ...value };
              addFields.parentCode = selectedDictCode.code;
              const success = await addDict(addFields);
              if (success) {
                handleModalVisible(false);
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            rowKey="id"
            type="form"
            columns={dictSubs}
          />
        </CreateForm>
        {stepFormValues && Object.keys(stepFormValues).length ? (
          <EditForm
            onSubmit={async (value) => {
              const success = await handleUpdate(value);
              if (success) {
                handleEditModalVisible(false);
                setStepFormValues({});
                if (actionRef.current) {
                  actionRef.current.reload();
                }
              }
            }}
            onOpenChange={(visible) => {
              if (!visible) {
                handleEditModalVisible(false);
                setStepFormValues({});
              }
            }}
            editModalVisible={editModalVisible}
            values={stepFormValues}
          />
        ) : null}
      </ProCard>
    </PageContainer>
  );
};

export default TableList;
